﻿


import Request from '../../base/request.js'
import Storage from '../../base/storage.js'
import { getMonthList, isImageFile, downloadfun, IgetDeptList, sumByKey, getRecentYears, queryURLParams, previewCom,throttle, debounce  } from "../../base/utils.js"
const Composition = (proxy) => {
    const data = reactive({
        uploadLock: false,
        previewInfo: {
            pdfurl: "",
            pdfOpen: false,
            previewShow: false,
            imgUrl: ""
        },
        urlinfo: {},
        uploadImg: {
            fileList: [

            ]
        },
        proxy: "",
        messageTest:null,
        formData: {
            TotalScore:100
        },
/*        TotalScore: 100,*/
        monthList: [],
        yearsList: [],
        userinfo: {

        },
        settingList: [
        ],

        deptList:[],
        pagination: {
            total: 0,
            current: 1,
            pageSize: 10,
            loading: true,
            showTotal: total => `总共 ${total} 项`,
            defaultPageSize: 10,
            showSizeChanger: true, // 是否显示pagesize选择
            showQuickJumper: false, // 是否显示跳转窗
        }
    })
    let params = toRefs(data)

    const methods = {

        IDeleteFile: (id) => {

            return new Promise((resolve, rej) => {
                Request({
                    url: "/Performance/DeleteFormFile",
                    method: 'post',
                    data: {
                        FileId: id
                    }
                }).then(res => {

                    resolve(res)
                }).catch(() => {
                    rej()
                })
            })


        },
        itemRender: (data, type) => {
            let uid = data.file.FileId

            var btnPreview = (e) => {
                let item = params.uploadImg.value.fileList.find(es => es.FileId == e)
                console.log(item)
                item.url = item.FilePath || item.url
                if (item.FileName.indexOf('.pdf') != -1) {
                    params.previewInfo.value.pdfUrl = item.url
                    params.previewInfo.value.pdfOpen = true
                } else {
                    params.previewInfo.value.imgUrl = item.url
                    params.previewInfo.value.previewShow = true
                }

            }
            var btnDownLoad = (e) => {
                let item = params.uploadImg.value.fileList.find(es => es.FileId == e)
                item.url = item.FilePath || item.url
                const { name, url } = item
                params.uploadLock.value = true
                downloadfun(name, url).finally(() => {
                    params.uploadLock.value = false
                })
            }
            var btnDelete = (e) => {
                const { FileId } = e.file
                if (FileId) {
                    params.uploadLock.value = true
                    methods.IDeleteFile(FileId).then(res => {
                        params.uploadImg.value.fileList = params.uploadImg.value.fileList.filter(e => e.FileId != FileId)
                        params.messageTest.value.success(res.Msg);
                    }).catch(err => {
                        console.log(err, 'err')
                    }).finally(() => {
                        params.uploadLock.value = false
                    })
                }
            }
            const previewBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { btnPreview(uid, type) }, src: "../Bussiness/img/svg/preview.svg", width: 20, height: 22 }, { default: () => '预览' })
            const downloadBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { btnDownLoad(uid, type) }, src: "../Bussiness/img/svg/download.svg", width: 20, height: 22 }, { default: () => '下载' })
            const deleteBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', src: "../Bussiness/img/svg/delete.svg", width: 18, height: 22 }, { default: () => '删除' })
            const FDBtn = h(antd.Popconfirm, {
                title: "确定删除此文件？确定后不可恢复",
                onConfirm: () => btnDelete(data, type)

            }, { default: () => [deleteBtn] })
            var btns = h('div', { style: "display:flex;margin-left:10px" }, {
                default: () => [
                    isImageFile(data.file.url) ? previewBtn : null,
                    downloadBtn,
                    params.urlinfo.value.type == 9 ? null : FDBtn
                ]
            })
            return h('div', { style: 'margin-top:10px; width:400px;align-items:center; display:flex;justify-content:space-between' }, {
                default: () => [
                    data.file.name, btns
                ]
            })

        },
        getDeptList: () => {
            return new Promise(async (resolve, rej) => {
                params.deptList.value = await IgetDeptList(Request)
                if (params.deptList.value) {
                    resolve(1)
                }
            })


        },
        IGetMonthReportDetail: () => {
            params.pagination.value.loading = true

            Request({
                url: "/Performance/GetMonthReportDetail",
                method: 'post',

                data: {
                    Id: params.urlinfo.value.id,

                }
            }).then(res => {

                params.settingList.value = res.Data.ItemList.map(e => {
                    e.CheckContent = e.SubcategoryName
                    e.UpdateUserName = e.UpdateUserName
                    return e
                })
                params.formData.value = res.Data
     
                params.uploadImg.value.fileList = res.Data.FileList.map(e => {
                    e.url = e.FilePath
                    e.name = e.FileName
                    e.old = true
                    return e
                })

                methods.nchange()
            }).finally(() => {
                params.pagination.value.loading = false
            })

        },

        onSubmit: (Status) => {

            methods.nchange()
            let obj = {
                ...params.formData.value,
                Status,
                ItemList: params.settingList.value,
                FileList: params.uploadImg.value.fileList.filter(e => !e.old).map(e => e.FileId)
            }
 

            if (Status == 1) {
                //let DeductionItems = params.settingList.value.filter(e => e.ItemScore != 0).length
                //let DeductionMark = params.settingList.value.filter(e => e.Remark != null).length



                function validateArray(arr) {
                    return arr.every(obj => {
                        // 检查属性a是否存在且非空（根据实际需求调整空值判断逻辑）
                        const hasA = obj.hasOwnProperty('ItemScore') && obj.ItemScore >0;

                        // 若存在a，则必须存在b且非空
                        if (hasA) {
                            return obj.hasOwnProperty('Remark') && obj.Remark !== null && obj.Remark !== '';
                        }

                        // 若不存在a，b可以不存在或存在
                        return true;
                    });
                }

                //alert(validateArray(params.settingList.value))


                if (!validateArray(params.settingList.value)) {
                    return params.messageTest.value.info('请检查扣分项是否填写扣分缘由');
                }
            }



            params.uploadLock.value = true

            if (params.urlinfo.value.type) {



                Request({
                    url: "/Performance/EditMonthReport",
                    method: 'post',
                    data: obj
                }).then(res => {
                    params.messageTest.value.info(res.Msg);
                    methods.onBack()

                }).finally(() => {
                    params.uploadLock.value = false
                })

            } else {


                Request({
                    url: "/Performance/AddMonthReport",
                    method: 'post',
                    data: obj
                }).then(res => {
                    params.messageTest.value.info(res.Msg);
                    methods.onBack()

                }).finally(() => {
                    params.uploadLock.value = false
                })
            

            }
        },




        IGetMonthTemplete: () => {
            params.uploadLock.value = true
            Request({
                url: "/Performance/GetMonthTemplete",
                method: 'post',
            }).then(res => {
                params.settingList.value = res.Data

            }).finally(() => {
                params.uploadLock.value = false
            })
        },

        // 然后在外面定义节流函数
        throttledUpdate: debounce((e) => {

            if (params.urlinfo.value.id) {
                Request({
                    url: "/Performance/UpdateMonthReportItem",
                    method: 'post',
                    data: e
                }).then(res => {
                    let item = params.settingList.value.find(es => es.id == e.id)
                    if (item) {
                        item.UpdateUserName = params.userinfo.value.UserName
                    }
                }).finally(() => {
                    //params.uploadLock.value = false
                })
            }
            //params.uploadLock.value=true
     
        }, 1000),
       
 
        handleChange: (info, index) => {
            let subarrys = info.fileList.filter(e => !e.old).map(e => e.originFileObj)
            if (!params.uploadLock.value) {
                params.uploadLock.value = true
                let formData = new FormData();
                for (let e of subarrys) {
                    formData.append('file', e)
                }
                Request({
                    url: `/download/uploadfile?Path=Performance`,
                    method: 'post',
                    data: formData
                }).then(res => {
                    params.uploadImg.value.fileList = params.uploadImg.value.fileList && params.uploadImg.value.fileList ?.length > 0 ? [
                        ...res.Data.map(e => {
                            const { FilePath, FileName } = e
                            e.url = FilePath
                            e.name = FileName
                            return e
                        }),
                        ...params.uploadImg.value.fileList.filter(e => e.FileId)
                    ] : [...res.Data.map(e => {
                        const { FilePath, FileName } = e
                        e.url = FilePath
                        e.name = FileName
                        return e
                    })]


                    params.uploadLock.value = false
                })

            }
        },
        nchange: (s,e) => {
            let res = 100 - sumByKey(params.settingList.value, 'ItemScore') < 0 ? 0 : 100 - sumByKey(params.settingList.value, 'ItemScore')
            params.formData.value.TotalScore = Number(res).toFixed(2)
            if (e) {
                methods.throttledUpdate(e)
            }
        
        },
        onBack: () => {
            window.location.href ='/Performance/PerformanceMeansureNew'
        },
        init: () => {
            if (proxy) {
                params.proxy.value = proxy
            }
            const { message } = antd
            params.messageTest.value = message
            params.messageTest.value.config({
                top: `10vh`,
                duration: 7,
                maxCount: 1,
                rtl: true,
            });
            let info = Storage.get('AccountInfo', true)
            params.userinfo.value=info
            params.monthList.value = getMonthList()
            params.yearsList.value = getRecentYears()
            params.urlinfo.value = queryURLParams()
            Request({
                url: "/Account/createJwtToken",
                method: 'post',
                data: {
                    "userName": info && info.UserNo
                }
            }).then(res => {
                Storage.set('token', res.Data, true)
          
                })


            params.formData.value.Months = dayjs().month()+1
            params.formData.value.Years = dayjs().year()
            params.formData.value.DepartmentId = params.userinfo.value.DepartmentId

   
            methods.getDeptList()
            if (params.urlinfo.value.id) {
      
                methods.IGetMonthReportDetail()
            } else { methods.IGetMonthTemplete() }
    


        },

       


    }
    const template = {
        imageModel: previewCom(params, methods).imageModel,
        pdfPopModel: previewCom(params, methods).pdfPopModel,
        bottomBtns: {
            template: `<div class="w-full bg-[#eeeeee] h-50  flex  items-center justify-end">
                    <a-space>
  <a-popconfirm
    title="确定执行此操作?"
    ok-text="确定"
    cancel-text="取消"
    @confirm="onSubmit(0)"
  >
        

 <a-button v-if="urlinfo.type!=9"   :loading="uploadLock" type="primary">保存</a-button>
  </a-popconfirm>
  <a-popconfirm
    title="确定执行此操作?"
    ok-text="确定"
    cancel-text="取消"
    @confirm="onSubmit(1)"
  >
   <a-button :loading="uploadLock" v-if="urlinfo.type!=9" type="primary">提交</a-button>
  </a-popconfirm>
                        <a-button v-on:click="onBack">返回</a-button>
                    </a-space>
                </div>`,
            setup() {

                return {
                    ...params,
                    ...methods,
                };
            }

        }
    }


    //let template = toRefs(vtemplate)
    return { // 返回对象给模板

        ...params,
        ...methods,
        template

    }
}


export default Composition





